package com.myfojing.mycloud;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.realm.Realm;
import io.realm.RealmResults;

public class MoreActivity extends AppCompatActivity {
    private final String TAG = "我的Chart";
    private Locale locale;
    private LineChart chart;
    // popup
    private TextView entry_date;
    //private int screen_width;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
    private SimpleDateFormat dateFormat_d = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
    // 广播
    private BroadcastReceiver receiver;
    // database
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more);
        // ui
        TextView description = (TextView) findViewById(R.id.more_description);
        chart = (LineChart) findViewById(R.id.more_chart);
        entry_date = (TextView) findViewById(R.id.more_entry_date);

/*      DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screen_width = metrics.widthPixels;*/

        // 标题
        Sensirion sensirion = getIntent().getParcelableExtra("model");
        description.setText(String.format(Locale.CHINA, "%s\t描述：%s\t地址：%s:%s",
                sensirion.getTitle(),
                sensirion.getDescription(),
                sensirion.getIp(),
                sensirion.getPort()));
        // 响应广播
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //Log.d(TAG, "收到广播");
                addEntry(intent);
            }
        };
        // locale
        locale = Locale.getDefault();
        // chart init
        init_chart(sensirion.getMac());

    }

    @Override
    protected void onResume() {
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
                new IntentFilter("event_rh"));
        // database
        realm = Realm.getDefaultInstance();
        super.onResume();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        realm.close();
        super.onPause();
    }

    //增加广播收到的节点
    private void addEntry(Intent intent) {
        // 提取data
        Bundle bundle = intent.getExtras();
        float t = bundle.getFloat("t");
        float h = bundle.getFloat("h");
        long timestamp = bundle.getLong("timestamp") * 1000;  // ms
        LineData data = chart.getLineData();
        if (data != null) {
            ILineDataSet set_temp = data.getDataSetByIndex(0);
            ILineDataSet set_h = data.getDataSetByIndex(1);

            set_temp.removeEntry(0);
            set_temp.addEntry(new Entry(timestamp, t));
            set_h.removeEntry(0);
            set_h.addEntry(new Entry(timestamp, h));
/*            data.addEntry(new Entry(timestamp, t), 0);
            data.addEntry(new Entry(timestamp, h), 0);*/
            data.notifyDataChanged();
            chart.notifyDataSetChanged();

            chart.setMaxVisibleValueCount(30);
            //chart.moveViewToX(set_temp.getEntryCount());
            chart.invalidate();
        }
    }

    // 初始化chart
    private void init_chart(String _mac) {
        chart.setDragEnabled(true);
        chart.setTouchEnabled(true);
        chart.setDrawGridBackground(false);

        Description desc = new Description();
        desc.setText("Temp/H");
        chart.setDescription(desc);
        chart.setMarker(new MyMarkerView(this, R.layout.activity_more_marker));
        // 左右滑动
/*        Matrix matrix = new Matrix();
        matrix.postScale(1.0f, 1.5f);
        chart.getViewPortHandler().refresh(matrix, chart, false);
        chart.animateX(1000);*/

        chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                entry_date.setText(String.format(locale, "时间: %s",
                        dateFormat_d.format((long) e.getX())));
            }

            @Override
            public void onNothingSelected() {

            }
        });

        // get record
        RealmResults<MyRecord> dataset = realm.where(MyRecord.class).equalTo("mac", _mac).findAll();
        // chart
        if (dataset.size() > 0) {
            List<Entry> entries_temp = new ArrayList<>();
            List<Entry> entries_h = new ArrayList<>();
            // 温湿度数据
            for (MyRecord record : dataset) {
                entries_temp.add(new Entry(record.getCreated_at(), record.getTemp()));
                entries_h.add(new Entry(record.getCreated_at(), record.getHum()));
            }
            // 折线数据
            // 温度
            LineDataSet set_temp = new LineDataSet(entries_temp, getString(R.string.termperature));
            set_temp.setColor(Color.RED);
            set_temp.setAxisDependency(YAxis.AxisDependency.RIGHT);
            // 湿度
            LineDataSet set_h = new LineDataSet(entries_h, getString(R.string.humidity));
            set_h.setColor(Color.BLUE);
            set_h.setAxisDependency(YAxis.AxisDependency.LEFT);

            List<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set_temp);
            dataSets.add(set_h);
            LineData lineData = new LineData(dataSets);

            // Axis 客制化
            XAxis xAxis = chart.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setValueFormatter(new MyXAxisValueFormatter());
            xAxis.setGranularity(1);
            xAxis.setAvoidFirstLastClipping(true);
            xAxis.setDrawGridLines(false);

            YAxis leftAxis = chart.getAxisLeft();
            leftAxis.setAxisMinimum(20);
            leftAxis.setAxisMaximum(90);
            leftAxis.setDrawGridLines(true);
            leftAxis.setValueFormatter(new MyLeftAxisValueFormatter());

            YAxis rightAxis = chart.getAxisRight();
            rightAxis.setAxisMinimum(-20);
            rightAxis.setAxisMaximum(50);
            rightAxis.setDrawLabels(true);

            chart.setData(lineData);
            chart.invalidate();
        }
    }

    private class MyXAxisValueFormatter implements IAxisValueFormatter {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return dateFormat.format(new Timestamp((long) value));
        }
    }

    private class MyLeftAxisValueFormatter implements IAxisValueFormatter {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return String.format(locale, "%2.0f%%", value);
        }
    }

    // maker view
    private class MyMarkerView extends MarkerView {
        private TextView entry_marker;
        private MPPointF mpPointF;

        public MyMarkerView(Context context, int layoutResource) {
            super(context, layoutResource);
            entry_marker = (TextView) findViewById(R.id.more_popup_entry);
        }

        @Override
        public void refreshContent(Entry e, Highlight highlight) {
            entry_marker.setText(String.format(locale, "%s, %2.1f",
                    dateFormat.format(new Timestamp((int) e.getX())), e.getY()));
            super.refreshContent(e, highlight);
        }

        @Override
        public MPPointF getOffset() {
            if (mpPointF == null) {
                mpPointF = new MPPointF(-(getWidth() / 2), -getHeight());
            }
            return mpPointF;
        }
    }

    // end
}
